package com.NULL.phony.filter;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.NULL.phony.Helper;

public class OneRingCall extends Service {
	public final static String ACTION = "com.NULL.phony.filter.ONE_RING_CALL";

	@Override
	public IBinder onBind(Intent arg0) {

		return null;
	}

	@Override
	public void onCreate() {
		TelephonyManager telManager = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);

		telManager.listen(
				new PhoneStateListener() {
					private int lastState;
					private long ringTime;
					private OneRingCall ctx;
					private long cheatThrodsheld = 5000;

					@Override
					public void onCallStateChanged(int currentState,
							String incomingNumber) {
						if (lastState == TelephonyManager.CALL_STATE_RINGING
								&&
								// at call end : ringing to idle
								currentState == TelephonyManager.CALL_STATE_IDLE
								&&
								// duration must be very short
								System.currentTimeMillis() - ringTime < cheatThrodsheld
								&&
								// must be unknown person
								!Helper.isInContact(ctx, incomingNumber)) {

							// notify
							Helper.notify(ctx,
									ctx.getString(R.string.BlockOneRingCall)
											+ ":" + incomingNumber);

							// record this call
							DB db = new DB(ctx);
							db.add(incomingNumber,
									ctx.getString(R.string.BlockOneRingCall));
							db.close();

							// remove this missing call
							ctx.getContentResolver().delete(
									CallLog.Calls.CONTENT_URI,
									CallLog.Calls.NUMBER + "=?",
									new String[] { incomingNumber });

							// remove this missing call notification

						}
						lastState = currentState;
						ringTime = System.currentTimeMillis();
					}

					public PhoneStateListener init(OneRingCall context,
							int state) {
						ctx = context;
						lastState = state;
						ringTime = System.currentTimeMillis();
						cheatThrodsheld = Long.parseLong(ctx
								.getString(R.string.OneRingCallCheatThreshold));
						return this;
					}

				}.init(this, telManager.getCallState()),
				PhoneStateListener.LISTEN_CALL_STATE);
	}

	public static void start(Context context) {
		Intent intent = new Intent(ACTION);
		context.startService(intent);
	}
}
